﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithms
{
    /// <summary>
    /// 将字符串以之字形展示并按行读取
    /// https://leetcode.com/problems/zigzag-conversion/
    /// </summary>
    public class ZigZagConversion
    {
        public static string Action1(string s, int numRows)
        {
            if (string.IsNullOrWhiteSpace((s)) ||numRows<1)
            {
                return "";
            }

            if (numRows == 1)
            {
                return s;
            }

            if (numRows == 2)
            {
                int loop = s.Length / 2;
                if (s.Length % 2 > 0)
                {
                    loop++;
                }

               StringBuilder str1= new StringBuilder();
                StringBuilder str2 = new StringBuilder();
                for (int i = 0; i < s.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        str1.Append((s[i]));
                    }
                    else
                    {
                        str2.Append(s[i]);
                    }
                }

                return str1.Append(str2).ToString();
            }
            //之字形个数
            int loopNum = s.Length / (2 * numRows - 2);
            if (s.Length % (2 * numRows - 2) > 0)
            {
                loopNum++;
            }
            ///高
            char[,] r= new char[loopNum*(numRows-1), numRows];

            for (int i = 0; i < loopNum; i++)
            {
                //本次循环取字符串的开始位置
                int start = i * (2*numRows - 2);
                for (int j = 0; j < 2*numRows-2; j++)
                {
                    if (start + j == s.Length)
                    {
                        break;
                    }
                    //本次循环x轴起始点
                    int xStart = i * (numRows - 1);
                    if (j < numRows)
                    {
                        r[xStart, j] = s[start + j];
                    }
                    else
                    {
                        int py = j - numRows + 1;//偏移值
                        r[xStart + py, numRows - 1 - py] = s[start + j];
                    }
                     
                }
           
            }

            StringBuilder outStr= new StringBuilder();

            for (int i = 0; i < numRows; i++)
            {
                for (int j = 0; j < loopNum * (numRows - 1); j++)
                {
                    char t = r[j, i];
                    if (t != 0)
                    {
                        outStr.Append(t);
                    }
                }
            }

            return  outStr.ToString();
        }
    }
}
